<?php   if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('infiniteAssort'))
{
        /**
		 * 对二维数组进行无限极分类函数(一定要存在父子关系)
		 * 调用实例
         * $data=array(
         *      array('id'=>1,name=>'分类1','parent'=>0),
         *      array('id'=>2,name=>'分类2','parent'=>0),
         *      array('id'=>3,name=>'分类3','parent'=>0),
         *      array('id'=>4,name=>'分类4','parent'=>1),
         *      array('id'=>5,name=>'分类5','parent'=>1),
         *      array('id'=>6,name=>'分类6','parent'=>2),
         *      array('id'=>7,name=>'分类7','parent'=>3),
         *      array('id'=>8,name=>'分类8','parent'=>7)
         * );
         * infiniteAssort($data,0,0,"parent","id",$result,"p_level");
         * print_r($result);
         * 
		 * @param array   $array			二维数组
		 * @param int     $parent			父类ID	
		 * @param int     $level			层次号
		 * @param string  $parentKeyName	父类键名	
		 * @param string  $sonKeyName	    子类键名
		 * @param mixed	  &$result		    保存最终结果
		 */
		function  infiniteAssort($array,$parent,$level,$parentKeyName,$sonKeyName,&$result,$levelName="level",$mode=1,$fields="")
		{
		    if($mode==1)
            {
    			for($i=0;$i<count($array);$i++)
    			{
    				if($array[$i][$parentKeyName]==$parent)
    				{
    					$array[$i][$levelName]=$level;
    					$sub[]=$array[$i];
    				}
    			}
                if(isset($sub) && count($sub)>0)
                {
                    for($j=0;$j<count($sub);$j++)
        			{
        				$result[]=$sub[$j];
        				infiniteAssort($array,$sub[$j][$sonKeyName],$level+1,$parentKeyName,$sonKeyName,$result,$levelName,$mode,$fields);
        			}
                }
            }
            else if($mode==2)
            {
                for($i=0;$i<count($array);$i++)
    			{
    				if($array[$i][$parentKeyName]==$parent)
    				{
    					$array[$i][$levelName]=$level;
    					$sub[]=$array[$i];
    				}
    			}
                if(isset($sub) && count($sub)>0)
                {
        			for($j=0;$j<count($sub);$j++)
        			{
        			    if(!empty($fields))
                        {
                            foreach($fields as $k=>$v)
                            {
                                $temp[$v]=$sub[$j][$k];
                            }
                            $result["children"][]=$temp;
                        }
                        else
                        {
                            $result["children"][]=$sub[$j];
                        }
        				
        				infiniteAssort($array,$sub[$j][$sonKeyName],$level+1,$parentKeyName,$sonKeyName,$result["children"],$levelName,$mode,$fields);
        			}
                }
            }
		}
}
if ( ! function_exists('authcode'))
{
    function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) 
    {

         $ckey_length = 4;                     

         $key = md5($key ? $key : UC_KEY);
         $keya = md5(substr($key, 0, 16));
         $keyb = md5(substr($key, 16, 16));
         $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

         $cryptkey = $keya.md5($keya.$keyc);
         $key_length = strlen($cryptkey);

         $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
         $string_length = strlen($string);

         $result = '';
         $box = range(0, 255);

         $rndkey = array();
         for($i = 0; $i <= 255; $i++) {
             $rndkey[$i] = ord($cryptkey[$i % $key_length]);
         }

         for($j = $i = 0; $i < 256; $i++) {
             $j = ($j + $box[$i] + $rndkey[$i]) % 256;
             $tmp = $box[$i];
             $box[$i] = $box[$j];
             $box[$j] = $tmp;
         }

         for($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
             $box[$a] = $box[$j];
            $box[$j] = $tmp;
             $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
         }

         if($operation == 'DECODE') {
            if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
                return substr($result, 26);
             } else {
                 return '';
             }
         } else {
             return $keyc.str_replace('=', '', base64_encode($result));
         }
    }
}
if ( ! function_exists('filter_character'))
{
    /**
     *  中文状态的字符转为英文状态的字符 
     **/
    function filter_character($str)
    {
        $patterns=array("/｛/","/｝/","/，/","/ /","/？/","/：/","/【/","/】/","/（/","/）/");
        $replaces=array("{","}",","," ","?",":","[","]","(",")");
        ksort($patterns);
        ksort($replaces);
        return preg_replace($patterns,$replaces,$str);
    }
}
if ( ! function_exists('do_upload'))
{
    function do_upload($data,$filter_suffix="",$upload_path="upload/",$options=array())
    {
       $CI =& get_instance();
       if(is_uploaded_file($data['tmp_name']))
       {
    	   $suffix=array_pop(explode(".",$data["name"]));
           if(!empty($filter_suffix) && !in_array(strtolower($suffix),$filter_suffix))
           {
                return FALSE;
           }
           $filename=md5(microtime()).".".$suffix;
    	   $path = $upload_path.date("Ym").'/';

    	   if(!is_dir($path)) mkdir($path , 0777 );
               
           if(move_uploaded_file($data['tmp_name'],$path .$filename))
    	   {
               $url = base_url().$path.$filename;
               if(isset($options["create_thumb"])&& $options["create_thumb"])
               {
                    $CI->load->library('image_lib');
                    $config['image_library'] = 'gd2';
                    $config['source_image'] = $path.$filename;
                    $config['create_thumb'] = TRUE;
                    $config['maintain_ratio'] = TRUE;
                    $config['width'] = 200;
                    $config['height'] = 150;
                    $config=array_merge($config,$options);
                    //$this->load->library('image_lib', $config);
                    $CI->image_lib->initialize($config); 
                    if($CI->image_lib->resize())
                    {
                        return array("thumb"=>substr_replace($url,$CI->image_lib->thumb_marker.".",strrpos($url,"."),1),"source"=>$url);
                    }  
               }
               else
               {
                    return $url;
               }
       		}
    	    return FALSE;
    	}
    	return FALSE;
    } 
}
if ( ! function_exists('filter_face_content'))
{
    function filter_face_content($content)
    {
        $face_url="http://banji.tongyi.com/static/images/gif/";
        $code = $content;
        $code=preg_replace("/\[@/i","<img src='".$face_url,$code);
        $code=preg_replace("/@\]/i",".gif'/>",$code);
        return $code;
    }
}
if ( ! function_exists('resizeImage'))
{
    function resizeImage($image,$width,$height,$scale) {
    	list($imagewidth, $imageheight, $imageType) = getimagesize($image);
    	$imageType = image_type_to_mime_type($imageType);
    	$newImageWidth = ceil($width * $scale);
    	$newImageHeight = ceil($height * $scale);
    	$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
    	switch($imageType) {
    		case "image/gif":
    			$source=imagecreatefromgif($image); 
    			break;
    	    case "image/pjpeg":
    		case "image/jpeg":
    		case "image/jpg":
    			$source=imagecreatefromjpeg($image); 
    			break;
    	    case "image/png":
    		case "image/x-png":
    			$source=imagecreatefrompng($image); 
    			break;
      	}
    	imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
    	
    	switch($imageType) {
    		case "image/gif":
    	  		imagegif($newImage,$image); 
    			break;
          	case "image/pjpeg":
    		case "image/jpeg":
    		case "image/jpg":
    	  		imagejpeg($newImage,$image,90); 
    			break;
    		case "image/png":
    		case "image/x-png":
    			imagepng($newImage,$image);  
    			break;
        }
    	
    	chmod($image, 0777);
    	return $image;
    }
}
//You do not need to alter these functions
if ( ! function_exists('resizeThumbnailImage'))
{
    function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale){
    	list($imagewidth, $imageheight, $imageType) = getimagesize($image);
    	$imageType = image_type_to_mime_type($imageType);
    	$newImageWidth = ceil($width * $scale);
    	$newImageHeight = ceil($height * $scale);
    	$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
    	switch($imageType) {
    		case "image/gif":
    			$source=imagecreatefromgif($image); 
    			break;
    	    case "image/pjpeg":
    		case "image/jpeg":
    		case "image/jpg":
    			$source=imagecreatefromjpeg($image); 
    			break;
    	    case "image/png":
    		case "image/x-png":
    			$source=imagecreatefrompng($image); 
    			break;
      	}
        
    	imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,$newImageHeight,$width,$height);
    	switch($imageType) {
    		case "image/gif":
    	  		imagegif($newImage,$thumb_image_name); 
    			break;
          	case "image/pjpeg":
    		case "image/jpeg":
    		case "image/jpg":
    	  		imagejpeg($newImage,$thumb_image_name,90); 
    			break;
    		case "image/png":
    		case "image/x-png":
    			imagepng($newImage,$thumb_image_name);  
    			break;
        }
    	chmod($thumb_image_name, 0777);
    	return $thumb_image_name;
    }
}
if(!function_exists("get_file_suffix"))
{
    function get_file_suffix($file)
    {
        $suffix	= strtolower(substr($file, (strrpos($file,".",1)+1)));
        return $suffix;
    }
}
/**  
* 格式化金额  
*  
* @param int $money  
* @param int $len  
* @param string $sign  
* @return string  
*/  
if(!function_exists("format_money"))
{
    function format_money($money, $len=2, $sign='￥'){   
        $negative = $money > 0 ? '' : '-';   
        $int_money = intval(abs($money));   
        $len = intval(abs($len));   
        $decimal = '';//小数   
        if ($len > 0) {   
            $decimal = '.'.substr(sprintf('%01.'.$len.'f', $money),-$len);   
        }   
        $tmp_money = strrev($int_money);   
        $strlen = strlen($tmp_money);   
        for ($i = 3; $i < $strlen; $i += 3) {   
            $format_money .= substr($tmp_money,0,3).',';   
            $tmp_money = substr($tmp_money,3);   
        }   
        $format_money .= $tmp_money;   
        $format_money = strrev($format_money);   
        return $sign.$negative.$format_money.$decimal;   
    }
}
/**
 * 检测是否已在二维数组中存在
 * @param   $needle 要检查的数组或者字符串
 * @param   $$haystack  目标数组
 * @param   $fields 要检查的字段数组
 * @return  boolean
 **/ 
if(!function_exists("in_multi_array"))
{
    function in_multi_array($needle,$haystack,$fields=null)
    {
        foreach($haystack as $v1)
        {
            $is_existe=true;
            if(empty($fields) && is_array($needle))
            {
                foreach($needle as $k2=>$v2)
                {
                    if($v1[$k2]!=$needle[$k2])
                    {
                        $is_existe=false;
                        break;
                    }
                }
            }
            else
            {
                foreach($fields as $v2)
                {
                    if($v1[$v2]!=(is_array($needle)?$needle[$v2]:$needle))
                    {
                        $is_existe=false;
                        break;
                    }
                }
            }
            if($is_existe)
            {
                return true;
            }
        }
        return false;
    }
}
/**
 * 返回数组的某一列
 * @author  nmx
 * @param   array   $arr    数组
 * @param   string  $field  列名
 * @return  array
 */ 
if(!function_exists("array_fields"))
{
    function array_fields($arr,$field)
    {
        foreach($arr as $v)
        {
            $result[]=$v[$field];
        }
        return $result;
    }
}